import React,{useEffect,useState} from "react";
import { Text, View,StyleSheet,Image,TouchableHighlight,TouchableOpacity, Linking,ScrollView, Alert,TextInput,Platform } from "react-native";
import * as S from "../Home/styles";
import { Avatar, HStack, Center, NativeBaseProvider ,ChevronRightIcon,useToast,ArrowBackIcon} from "native-base";
import {launchImageLibrary,launchCamera} from 'react-native-image-picker';
import { /*RFValue*/ } from "react-native-responsive-fontsize";
import Icon from 'react-native-vector-icons/Ionicons';
import { useGlobal } from '../../utils/GlobalContext';
import { saveUeser,uploadImage } from "../../services/user";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { CommonActions } from '@react-navigation/native';


const Title = ({navigation}:any)=>{
  return(
    <View style={styles.titleBox}>
      <TouchableOpacity
        style={styles.backBtn}
        onPress={() => {
          navigation.goBack()
        }}
      >
        <ArrowBackIcon size="5" />
      </TouchableOpacity>
      <Text style={styles.titlText}>个人信息</Text>
    </View>
  )
}

const UserInfonBox = ({route,navigation}:any)=>{

  const { state, dispatch } = useGlobal();

 

  const [ nickName, setNickName ] = useState('');
  const [ phone, setPhone ] = useState('');
  const [ userId, setUserId ] = useState('');

  const [imageUri, setimageUri] = useState(null)
  // const [imageObj, setimageObj] = useState({})

  const setInfo = ()=>{

    // Alert.alert(state.userInfo.avatar)

    setNickName(state.userInfo.nickName)
    setPhone(state.userInfo.phone)
    setUserId(state.userInfo.id)
    setimageUri(state.userInfo.avatar)
    // setimageObj({uri:state.userInfo.avatar})
  }

  useEffect(() => {
    
    setInfo()


    return () => {

    };



  }, []);

  const pickImage = () => {
    launchImageLibrary(
      {
        mediaType: 'photo',
        selectionLimit: 1,
        includeBase64: false,
        maxWidth: 500,
        maxHeight: 500,
        quality:0.5
      },
      async res => {
        // console.log(res)
        const curFiles = res.assets;
        let result = {}
        result = curFiles[0]
        const formData = new FormData();
        formData.append('images', {
          uri: result.uri,
          type: result.type,
          name: result.fileName,
        });

        uploadImage(formData).then(res=>{
          console.log(res.data[0])
          setimageUri(res.data[0])
        })

        // result = curFiles[0]
        // console.log(result)
        // await setimageObj(result)
        
      }
      )
  };

  
  const subMit = ()=>{
    // dispatch({ type:'SET_USER' , payload:{...state.userInfo,avatar:'https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80',nickName:'ooooo'}})
    let obj = {
      nickName:nickName,
      avatar:imageUri
    }
    console.log(obj)

    saveUeser(obj).then(res=>{
      if(res.code == 0){
        const getUserInfo = route.params?.getUserInfo;
        if (getUserInfo) {
          getUserInfo();
        }
        navigation.goBack();
      }
    })




    
  }
  const logOut = ()=>{
    dispatch({ type:'SET_TOKEN' , payload:'' })
    dispatch({ type:'SET_USER' , payload:{} })
    AsyncStorage.removeItem("TOKEN")
    // navigation.replace('Login')
    navigation.dispatch(
      CommonActions.reset({
        index: 0,
        routes: [{ name: 'Login' }] // 设置新页面的路由
      })
    );
  }
  const onChange = (text:string,type:number)=>{
    if(type == 1){
      setNickName(text)
    }else{
      setPhone(text)
    }
  }

  return(
    <View style={styles.content}>
      <View style={styles.contentBox}>
        <View style={styles.contentItem}>
          <Text style={styles.itemLeft}>用户ID</Text>
          <Text style={styles.itemRight}>{userId}</Text>
        </View>
      </View>
      <View style={styles.contentBox}>
        <View style={[styles.contentItem,styles.contentItemLine]}>
          <Text style={styles.itemLeft}>头像</Text>
          <TouchableOpacity onPress={()=>{
             pickImage()
            }}>
            <View style={{}}>
              {/* <Image style={[{ width:40,height:40,borderRadius:100}]} source={{uri:imageUri}} /> */}
              <Avatar style={[{ width:40,height:40,borderRadius:100}]} source={{
                  uri: imageUri
                  }}>
                  <Image  style={[{ width:40,height:40,borderRadius:100}]} source={require("../../assets/images/profile/avatar_default.png")} alt="" />
              </Avatar>
            </View>
          </TouchableOpacity>


        </View>
        <View style={[styles.contentItem,styles.contentItemLine]}>
          <Text style={styles.itemLeft}>昵称</Text>
          <TextInput
            style={styles.input}
            placeholder='请输入'
            placeholderTextColor='#8E8E93'
            onChangeText={text => onChange(text,1)}
            value={nickName}
          />
        </View>
        <View style={[styles.contentItem]}>
          <Text style={styles.itemLeft}>手机号</Text>
          <TextInput
            style={styles.input}
            keyboardType="phone-pad"
            placeholder='请输入'
            placeholderTextColor='#8E8E93'
            onChangeText={text => onChange(text,2)}
            value={phone}
            editable={phone?false:true}
          />
        </View>
      </View>

      <View>
        <TouchableOpacity
          style={styles.subBtn}
          onPress={
            ()=>{
              subMit()
            }
          }
        >
          <View>
            <Text style={styles.subBtnText}>保存</Text>
          </View>
        </TouchableOpacity>
      </View>
      <View>
        <TouchableOpacity
          style={[styles.subBtn,{backgroundColor: '#E5E5EA'}]}
          onPress={
            ()=>{
              logOut()
            }
          }
        >
          <View>
            <Text style={styles.subBtnText}>退出登录</Text>
          </View>
        </TouchableOpacity>
      </View>

    </View>
  )
}

const UserCenter = ({route,navigation}:any) => {
  return (
    <S.GrayContainer>
      <NativeBaseProvider>
       <View style={styles.container}>
          <Title navigation={navigation}/>
          <ScrollView style={{height:'100%'}} showsVerticalScrollIndicator={false}>
            <UserInfonBox route={route} navigation={navigation}/>
          </ScrollView>
       </View>
      </NativeBaseProvider>
      
    </S.GrayContainer>
  );
};

export default UserCenter;
const styles = StyleSheet.create({
  container:{
    height:"100%",
    width:'100%',
    // alignItems:'center',
    paddingHorizontal:18,
  },
  titleBox:{
    width:'100%',
    position:'relative',
    alignItems:'center',
    height:40,
    justifyContent:"center",
    marginBottom:16,
  },
  backBtn:{
    position:'absolute',
    left:0,
    backgroundColor:'#fff',
    width:40,
    height:40,
    display:'flex',
    alignItems:'center',
    justifyContent:'center',
    borderRadius:100,
    
    shadowColor: Platform.OS === 'android' ? '' : 'rgba(0, 0, 0, 0.08)', // 阴影颜色
    shadowOffset: { width: 0, height: 2 }, // 阴影偏移
    shadowOpacity: 1, // 阴影不透明度
    shadowRadius: 8, // 阴影半径
    elevation: 3, // 阴影深度
  },
  titlText:{
    fontSize:16,
    fontWeight:'600',
    color:'#000000'
  },
  content:{},
  contentBox:{
    paddingHorizontal:16,
    backgroundColor:'#fff',
    borderRadius:16,
    marginBottom:16,
  },
  contentItem:{
    paddingVertical:14,
    flexDirection:'row',
    justifyContent:'space-between',
    alignItems:'center'
  },
  contentItemLine:{
    borderBottomWidth:1,
    borderColor:'#eee'
  },
  itemLeft:{
    fontSize:16,
    color:'#000000',
    fontWeight:'400',
  },
  itemRight:{
    fontSize:16,
    color:'#8E8E93',
    fontWeight:'400',
  },
  subBtn:{
    marginTop:20,
    width:'100%',
    backgroundColor:'#C6E0F7',
    borderRadius:16,
    height:50,
    alignItems:'center',
    justifyContent:'center'
  },
  subBtnText:{
    color:'#414F66',
    fontSize:14,
    fontWeight:'700'
  },
  input:{
    fontSize:16,
    height:"100%",
    margin:0,
    padding:0,
    color:'#000'
  },

})
